package com.popreal.scheduler.interceptor;

import java.sql.Connection;
import java.sql.DriverManager;

import javax.servlet.ServletContext;

import net.vsame.url2sql.helper.Url2SqlContext;
import net.vsame.url2sql.url.Interceptor;
import net.vsame.url2sql.url.impl.UrlMapping;
import net.vsame.url2sql.url.impl.UrlMapping.Chain;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.popreal.scheduler.MainExecutor;
import com.popreal.scheduler.bae.BAEConfig;
import com.popreal.scheduler.helper.BAERedisHelper;

public class BaseInterceptor implements Interceptor {
	
	public static WebApplicationContext springContext;

	@Override
	public void init(UrlMapping urlMapping, ServletContext servletContext) {
		System.setProperty("https.protocols", "TLSv1.2");//支持 PayPal
		springContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		
		if(System.getenv("SERVER_SOFTWARE") == null){
			devInit();
		} else {
			baeInit();
		}
		
		MainExecutor mainExecutor = springContext.getBean("mainExecutor", MainExecutor.class);
		System.out.println("interceptor thread begin----------");
		mainExecutor.start();
		System.out.println("interceptor thread end----------");
	}
	
	private void devInit(){
		final ComboPooledDataSource dataSource = springContext.getBean("dataSource", ComboPooledDataSource.class);
		Url2SqlContext.setConnSource(new Url2SqlContext.ConnSource() {
			
			@Override
			public Connection getConnection() {
				try {
					return dataSource.getConnection();
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		});
	}
	
	private void baeInit() {
		final BAEConfig baeConfig = springContext.getBean(BAEConfig.class);
		
		// MySql 
        try {
			Class.forName(baeConfig.getMysqlClassName());
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
		Url2SqlContext.setConnSource(new Url2SqlContext.ConnSource() {
			@Override
			public Connection getConnection() {
				try {
					return DriverManager.getConnection(baeConfig.getMysqlUrl(), baeConfig.getAk(), baeConfig.getSk());
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		});
		
		// Redis
		BAERedisHelper.setBaeConfig(baeConfig);
		System.out.println("BAE INIT");
	}

	@Override
	public void invoke(Chain chain) {
		chain.next();
	}

	@Override
	public void destroy() {
		
	}

}
